using System;
using LegoBotPrima.Actions;
using LegoBotPrimaAbstractions;
using LegoBotPrimaAbstractions.Extensions;

namespace LegoBotPrima
{
    public class BotActionController : IBotActionController
    {
        public ILegoBotPrimaWorkflow Workflow { get; private set; }
        public IWorkflowLogger Logger { get; private set; }

        public void Initialize(ILegoBotPrimaWorkflow workflow, IWorkflowLogger logger)
        {
            Ensure.IsNotNull(workflow, "workflow");
            Ensure.IsNotNull(logger, "logger");

            Workflow = workflow;
            Logger = logger;
        }

        public IBotAction OnSetAction(IBotAction previousAction, IBotAction newAction)
        {
            return newAction;
        }
        public RunMode OnSetActionChangeMode(RunMode currentMode, IBotAction previousAction, IBotAction newAction)
        {
            if (newAction is StartAutonomousBotAction)
            {
                Workflow.SetAction(new Rotate360BotAction());
                return RunMode.Autonomous;
            }
            if (newAction is StartManualBotAction)
            {
                return RunMode.Manual;
            }
            if (newAction is StopAllBotAction)
            {
                return RunMode.Stop;
            }
            return currentMode;
        }
        public void OnEndAction(IBotAction action)
        {
            if (Workflow.Mode == RunMode.Manual)
            {
                return;
            }


            Workflow.SetAction(action.RequestedNextAction ?? new StopBotAction());

            /*if (action is Rotate360BotAction)
            {
                var rotate360 = action as Rotate360BotAction;

                var random = GetRandomOpenAngle(rotate360);

                if (random < 0)
                {
                    Workflow.SetAction(new WaitBotAction { Seconds = 5, AfterWaitAction = new Rotate360BotAction() });
                }
                else
                {
                    Workflow.SetAction(new GoToAngleBotAction { Angle = random });
                }
            }
            else if (action is WaitBotAction)
            {
                var wait = action as WaitBotAction;
                if (wait.AfterWaitAction != null)
                {
                    Workflow.SetAction(wait.AfterWaitAction);
                }
            }
            else if (action is GoToAngleBotAction)
            {
                Workflow.SetAction(new ForwardBotAction());
            }
            else if (action is ForwardBotAction)
            {
                Workflow.SetAction(new WaitBotAction { Seconds = 1, AfterWaitAction = new Rotate360BotAction() });
            }*/
        }


    }
}